#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
  int pipefd[2] = {0};
  if (pipe(pipefd) != 0){
    perror("pipe failed\n");
    return 1;
  }

  printf("pipefd[0] = %d\n", pipefd[0]);//3 读取端[0]
  printf("pipefd[1] = %d\n", pipefd[1]);//4 写入端[1]
  //让父进程读取，让子进程写入
  if (fork() == 0){
    //child
    close(pipefd[0]);
    const char* msg = "hello world\n";
    //int count = 0;
    while (1){
      //只要管道没有满，就一直写入(字节流)
      write(pipefd[1], msg, strlen(msg));
      //printf("%s\n", msg);
      //write(pipefd[1], "a", 1);
      //printf("count = %d\n", count);
      //count++;
      //close(pipefd[1]);
      //break;
    }
  }
  //father
  close(pipefd[1]);
  while (1){
    sleep(1);
    char buffer[64] = {0};
    //read 返回值为0 意味着子进程关闭文件描述符
    //加入管道里有数据，就一直读(字节流)
    ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1);
    //buffer[s] = 0;
    //printf("father take: %s\n", buffer);
    if (s == 0){
      printf("read end\n");
      break;
    }
    else if (s > 0){
      buffer[s] = 0;
      printf("child say# %s", buffer);
      close(pipefd[0]);
    }
    else{ 
      break;
    }
  }
  int status = 0;
  waitpid(-1, &status, 0);
  if (WIFEXITED(status))
  {
    printf("exit code = %d\n", WEXITSTATUS(status));
  }
  else 
  {
    printf("receive signal = %d\n", status & 0x7f);
  }
  return 0;
}


